package com.ruoyi.produce.material.service;


import com.ruoyi.DingDing.Domain.DingDingText;
import com.ruoyi.constant.ERPConstant;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.personnel.oa.approve.domain.ApproveDomain;
import com.ruoyi.personnel.oa.approve.mapper.ApproveMapper;
import com.ruoyi.personnel.oa.sequence.service.IApproveSequenceService;
import com.ruoyi.produce.material.domain.ProduceMaterialRequisition;
import com.ruoyi.produce.material.domain.ProduceMaterialRequisitionList;
import com.ruoyi.produce.material.mapper.ProduceMaterialMapper;
import com.ruoyi.psi.inventory.record.domain.StockInRecord;
import com.ruoyi.psi.inventory.record.mapper.StockInRecordMapper;
import com.ruoyi.psi.inventory.record.service.IStockInRecordService;
import com.ruoyi.psi.inventory.recordOut.domain.StockOutRecord;
import com.ruoyi.psi.inventory.recordOut.service.IStockOutRecordService;
import com.ruoyi.utils.ID.IdUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.List;

/**
 * 物料领、补、退信息
 * 业务执行层
 * 修改：lsy 2021.8.20
 */
@Service
public class ProduceMaterialServiceImpl implements IProduceMaterialService {
    @Autowired
    private ProduceMaterialMapper produceMaterialMapper;
    @Autowired
    private IProduceMaterialService produceMaterialService;
    @Autowired
    private IdUtil idUtil;
    @Autowired
    private IApproveSequenceService approveSequenceService;
    @Autowired
    private ApproveMapper approveMapper;
    @Autowired
    private StockInRecordMapper stockInRecordMapper; //入库记录
    @Autowired
    private IStockInRecordService stockInRecordService; //入库记录
    @Autowired
    private IStockOutRecordService stockOutRecordService; //出库记录

    /**
     * 物料领、补、退信息查询
     *
     * @param produceMaterialRequisition
     * @return
     */
    @Override
    public List<ProduceMaterialRequisition> selectProduceMaterialRequisitionList(ProduceMaterialRequisition produceMaterialRequisition) {
        List<ProduceMaterialRequisition> produceMaterialRequisitions = produceMaterialMapper.selectProduceMaterialRequisitionList(produceMaterialRequisition);
        for (int i = 0; i < produceMaterialRequisitions.size(); i++) {
            if (StringUtils.isNotNull(produceMaterialMapper.selectProduceMaterialRequisitionListListById(produceMaterialRequisitions.get(i).getMaterialRequisitionId()))) {
                //若存在
                produceMaterialRequisitions.get(i).setProduceMaterialRequisitionLists(produceMaterialMapper.selectProduceMaterialRequisitionListListById(produceMaterialRequisitions.get(i).getMaterialRequisitionId()));
            }
        }
        return produceMaterialRequisitions;
    }

    /**
     * 按编号查询
     *
     * @param materialRequisitionId 物料领、补、退信息编号
     * @return
     */
    @Override
    public ProduceMaterialRequisition selectProduceMaterialRequisitionById(String materialRequisitionId) {
        ProduceMaterialRequisition produceMaterialRequisition = produceMaterialMapper.selectProduceMaterialRequisitionById(materialRequisitionId);
        if (StringUtils.isNotNull(produceMaterialMapper.selectProduceMaterialRequisitionListListById(produceMaterialRequisition.getMaterialRequisitionId()))) {
            //若存在
            produceMaterialRequisition.setProduceMaterialRequisitionLists(produceMaterialMapper.selectProduceMaterialRequisitionListListById(produceMaterialRequisition.getMaterialRequisitionId()));
        }
        return produceMaterialRequisition;
    }

    /**
     * 物料领、补、退信息新增
     *
     * @param produceMaterialRequisition
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertProduceMaterialRequisition(ProduceMaterialRequisition produceMaterialRequisition) throws Exception {
        if (StringUtils.isNotNull(produceMaterialMapper.selectProduceMaterialRequisitionById(produceMaterialRequisition.getMaterialRequisitionId()))) {
            //存在
            return 0;
        }
        //不存在
        String materialRequisitionId = idUtil.createMaterialRequisitionId(produceMaterialRequisition.getMaterialRequisitionType());//自动生成编号
        produceMaterialRequisition.setMaterialRequisitionId(materialRequisitionId);//主表添加编号
        ApproveDomain approve = new ApproveDomain(materialRequisitionId, "领退补料单审批", ERPConstant.APPROVAL_TYPE_PRODUCE_MATERIAL, produceMaterialRequisition.getStaffPickingId()); //新增审批
        approve.setCurrentApprover(approveSequenceService.getLowestRoleId(ERPConstant.APPROVAL_TYPE_PRODUCE_MATERIAL));
        approveMapper.insertApprove(approve);
        Long currentApprover = approve.getCurrentApprover();
        DingDingText dingDingText = new DingDingText();
        dingDingText.BatchRobotText(currentApprover);
        produceMaterialMapper.insertProduceMaterialRequisition(produceMaterialRequisition);//物料领、补、退信息据
        List<ProduceMaterialRequisitionList> produceMaterialRequisitionLists = produceMaterialRequisition.getProduceMaterialRequisitionLists();//物料领、补、退信息产品信息
        for (int i = 0; i < produceMaterialRequisitionLists.size(); i++) {
            produceMaterialRequisitionLists.get(i).setMaterialRequisitionId(materialRequisitionId); //子表添加编号
            produceMaterialMapper.insertProduceMaterialRequisitionList(produceMaterialRequisitionLists.get(i));//物料领、补、退信息产品信息
        }

        return 1;

    }

    /**
     * 领退补料出入库
     * 用于app
     * @param produceMaterial
     * @return
     */
    @Override
    public int produceMaterialStorage(ProduceMaterialRequisition produceMaterial) {
        if (!StringUtils.isNotNull(produceMaterialMapper.selectProduceMaterialRequisitionById(produceMaterial.getMaterialRequisitionId()))) {
            //不存在
            return 0;
        }
        ProduceMaterialRequisition produceMaterialRequisition = produceMaterialService.selectProduceMaterialRequisitionById(produceMaterial.getMaterialRequisitionId());
        String materialRequisitionType = produceMaterialRequisition.getMaterialRequisitionType();//判断来源类型
        List<ProduceMaterialRequisitionList> produceMaterialRequisitionListOld = produceMaterialRequisition.getProduceMaterialRequisitionLists();//原领料单子表
        List<ProduceMaterialRequisitionList> produceMaterialRequisitionLists = produceMaterial.getProduceMaterialRequisitionLists();//物料领、补、退信息产品信息
        for (int i = 0; i < produceMaterialRequisitionLists.size(); i++) {
            // 判断原领料单的子表产品
            boolean existFlag = false;
            for (ProduceMaterialRequisitionList sl : produceMaterialRequisitionListOld) {
                if (sl.getProduceId().equals(produceMaterialRequisitionLists.get(i).getProduceId())) {
                    existFlag = true;
                    break;
                }
            }
            if (existFlag) {
                //存在
                produceMaterialMapper.updateProduceMaterialRequisitionList(produceMaterialRequisitionLists.get(i)); //更新子表
            } else {
                produceMaterialMapper.insertProduceMaterialRequisitionList(produceMaterialRequisitionLists.get(i)); //新增子表
            }

            String stockInId = produceMaterialRequisitionLists.get(i).getAssociationId();
            StockInRecord stockInRecord = stockInRecordMapper.selectStockInRecordByAssociationId(stockInId); //该子表领料产品的入库记录
//            WarehouseListDomain warehouseListDomain = new WarehouseListDomain(); // 仓库子表的对象
//            warehouseListDomain.setWarehouseId(stockInRecord.getWarehouseId());
//            warehouseListDomain.setProduceId(stockInRecord.getProduceId());
//                        warehouseListDtos = warehouseMapper.selectWarehouseListListById(stockInRecord.getWarehouseId());
            //1:领料 2:补料 3:退料
            if (materialRequisitionType.equals("1") || materialRequisitionType.equals("2")) {
                //新增一条出库记录
                StockOutRecord stockOutRecord = new StockOutRecord(stockInRecord.getStockInId(), ERPConstant.LingLiao, produceMaterialRequisition.getStaffPickingId(), stockInRecord.getProduceId(), stockInRecord.getWarehouseId(), produceMaterialRequisitionLists.get(i).getMaterialRequisitionNumber());
                stockOutRecordService.insertStockOutRecord(stockOutRecord);
            } else if (materialRequisitionType.equals("3")) {
                //修改原入库数量 （库存数量 + 退货数量作为修改数量）
                stockInRecord.setWarehousingNumber(stockInRecord.getWarehousingNumber() + produceMaterialRequisitionLists.get(i).getMaterialRequisitionNumber());
                stockInRecordService.updateStockInRecord(stockInRecord);
            }
            // 每次子表延迟1s存入数据库
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        return 1;
    }

    /**
     * 物料领、补、退信息更新
     *
     * @param produceMaterialRequisition
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateProduceMaterialRequisition(ProduceMaterialRequisition produceMaterialRequisition) throws Exception {
        if (!StringUtils.isNotNull(produceMaterialMapper.selectProduceMaterialRequisitionById(produceMaterialRequisition.getMaterialRequisitionId()))) {
            //不存在
            return 0;
        }
        //存在物料领、补、退信息单据
        produceMaterialMapper.updateProduceMaterialRequisition(produceMaterialRequisition);//物料领、补、退信息单据
        String materialRequisitionType = produceMaterialRequisition.getMaterialRequisitionType();//判断来源类型
//        List<WarehouseListDto> warehouseListDtos = warehouseMapper.selectWarehouseListListById(produceMaterialRequisition.getWarehouseId()); // 查询该仓库的产品列表
        List<ProduceMaterialRequisitionList> produceMaterialRequisitionListOld = produceMaterialMapper.selectProduceMaterialRequisitionListListById(produceMaterialRequisition.getMaterialRequisitionId());
        List<ProduceMaterialRequisitionList> produceMaterialRequisitionListNew = produceMaterialRequisition.getProduceMaterialRequisitionLists();//物料领、补、退信息产品信息
        for (int i = 0; i < produceMaterialRequisitionListNew.size(); i++) {
            // 新建仓库子表的对象
//            WarehouseListDomain warehouseListDomain = new WarehouseListDomain();
//            warehouseListDomain.setWarehouseId(produceMaterialRequisition.getWarehouseId());
//            warehouseListDomain.setProduceId(produceMaterialRequisitionListNew.get(i).getProduceId());
            ProduceMaterialRequisitionList produceMaterialRequisitionList = produceMaterialMapper.selectProduceMaterialRequisitionListById(produceMaterialRequisition.getMaterialRequisitionId(), produceMaterialRequisitionListNew.get(i).getProduceId());
            if (StringUtils.isNotNull(produceMaterialRequisitionList)) {
                for (int j = 0; j < produceMaterialRequisitionListOld.size(); j++) {
                    if (produceMaterialRequisitionListOld.get(j).getProduceId().equals(produceMaterialRequisitionList.getProduceId())) {
                        produceMaterialRequisitionListOld.remove(j);
                        break;
                    }
                }
                //存在物料领、补、退信息详细
                //更新
                //1:领料 2:补料 3:退料
//                if (materialRequisitionType.equals("1") || materialRequisitionType.equals("2")) {
//                    for (WarehouseListDto s : warehouseListDtos) {
//                        // 遍历仓库
//                        if (produceMaterialRequisitionListNew.get(i).getProduceId().equals(s.getProduceId())) {
//                            // 该产品存在，更新产品数量，产品数量 = 原库存数 + 该产品原出库的数量 - 新出库数量
//                            warehouseListDomain.setProductNumber(s.getProductNumber() + produceMaterialRequisitionList.getMaterialRequisitionNumber() - produceMaterialRequisitionListNew.get(i).getMaterialRequisitionNumber());
//                            break; //终止循环
//                        }
//                    }
//                    warehouseMapper.updateWarehouseList(warehouseListDomain); //更新库存数
//                } else if (materialRequisitionType.equals("3")) {
//                    for (WarehouseListDto s : warehouseListDtos) {
//                        // 遍历仓库
//                        if (produceMaterialRequisitionListNew.get(i).getProduceId().equals(s.getProduceId())) {
//                            // 该产品存在，更新产品数量，产品数量 = 原库存数 - 该产品原入库数量 + 新入库的数量
//                            warehouseListDomain.setProductNumber(s.getProductNumber() - produceMaterialRequisitionList.getMaterialRequisitionNumber() + produceMaterialRequisitionListNew.get(i).getMaterialRequisitionNumber());
//                            break; //终止循环
//                        }
//                    }
//                    warehouseMapper.updateWarehouseList(warehouseListDomain); //更新库存数
//                }
                produceMaterialMapper.updateProduceMaterialRequisitionList(produceMaterialRequisitionListNew.get(i));
            } else {//新增
//                if (materialRequisitionType.equals("2")) {
//                    for (WarehouseListDto s : warehouseListDtos) {
//                        // 遍历仓库
//                        if (produceMaterialRequisitionListNew.get(i).getProduceId().equals(s.getProduceId())) {
//                            // 该产品存在，更新产品数量，产品数量 = 原库存数 - 产品出库数量
//                            warehouseListDomain.setProductNumber(s.getProductNumber() - produceMaterialRequisitionListNew.get(i).getMaterialRequisitionNumber());
//                            break; //终止循环
//                        }
//                    }
//                    // 该产品存在，更新库存数量
//                    warehouseMapper.updateWarehouseList(warehouseListDomain);
//                }
                produceMaterialMapper.insertProduceMaterialRequisitionList(produceMaterialRequisitionListNew.get(i));
            }
        }
        // 说明有删除的对象
        for (int i = 0; i < produceMaterialRequisitionListOld.size(); i++) {
//            // 新建仓库子表的对象
//            WarehouseListDomain warehouseListDomain = new WarehouseListDomain();
//            warehouseListDomain.setWarehouseId(produceMaterialRequisition.getWarehouseId());
//            warehouseListDomain.setProduceId(produceMaterialRequisitionListOld.get(i).getProduceId());
//            //1:领料 2:补料 3:退料
//            if (materialRequisitionType.equals("1") || materialRequisitionType.equals("2")) {
//                for (WarehouseListDto s : warehouseListDtos) {
//                    // 遍历仓库
//                    if (produceMaterialRequisitionListOld.get(i).getProduceId().equals(s.getProduceId())) {
//                        // 该产品存在，更新产品数量，产品数量 = 原库存数 + 该产品原出库的数量
//                        warehouseListDomain.setProductNumber(s.getProductNumber() + produceMaterialRequisitionListOld.get(i).getMaterialRequisitionNumber());
//                        break; //终止循环
//                    }
//                }
//                warehouseMapper.updateWarehouseList(warehouseListDomain); //更新库存数
//            } else if (materialRequisitionType.equals("3")) {
//                for (WarehouseListDto s : warehouseListDtos) {
//                    // 遍历仓库
//                    if (produceMaterialRequisitionListOld.get(i).getProduceId().equals(s.getProduceId())) {
//                        // 该产品存在，更新产品数量，产品数量 = 原库存数 - 该产品原入库数量
//                        warehouseListDomain.setProductNumber(s.getProductNumber() - produceMaterialRequisitionListOld.get(i).getMaterialRequisitionNumber());
//                        break; //终止循环
//                    }
//                }
//                warehouseMapper.updateWarehouseList(warehouseListDomain); //更新库存数
//            }
            //最后将要删除的子标记录删除
            produceMaterialMapper.deleteProduceMaterialRequisitionListById(produceMaterialRequisitionListOld.get(i).getMaterialRequisitionId(), produceMaterialRequisitionListOld.get(i).getProduceId());
        }
        return 1;
    }

    /**
     * 更新物料领、补、退信息删除标志位
     *
     * @param produceMaterialRequisition
     * @return
     */
    @Override
    public int updateProduceMaterialRequisitionDeleteFlag(ProduceMaterialRequisition produceMaterialRequisition) {
        return produceMaterialMapper.updateProduceMaterialRequisitionDeleteFlag(produceMaterialRequisition);
    }

    /**
     * 物料领、补、退信息详细查询
     *
     * @param produceMaterialRequisitionList
     * @return
     */
    @Override
    public List<ProduceMaterialRequisitionList> selectProduceMaterialRequisitionListList(ProduceMaterialRequisitionList produceMaterialRequisitionList) {
        return produceMaterialMapper.selectProduceMaterialRequisitionListList(produceMaterialRequisitionList);
    }

    /**
     * 查询物料领、补、退信息对应的所有产品详细
     *
     * @param materialRequisitionId 物料领、补、退信息编号
     * @return
     */
    @Override
    public List<ProduceMaterialRequisitionList> selectProduceMaterialRequisitionListListById(String materialRequisitionId) {
        return produceMaterialMapper.selectProduceMaterialRequisitionListListById(materialRequisitionId);
    }

    /**
     * 查询物料领、补、退信息对应的指定产品详细
     *
     * @param materialRequisitionId 物料领、补、退信息编号
     * @param produceId             产品编号
     * @return
     */
    @Override
    public ProduceMaterialRequisitionList selectProduceMaterialRequisitionListById(String materialRequisitionId, String produceId) {
        return produceMaterialMapper.selectProduceMaterialRequisitionListById(materialRequisitionId, produceId);
    }

    /**
     * 获取加工单对应物料信息
     * 新增领料单
     *
     * @param workSheetId 加工单号
     * @return
     */
    @Override
    public List<ProduceMaterialRequisitionList> getMaterialRequisitionFromWorkSheet(String workSheetId) {
        List<ProduceMaterialRequisitionList> produceMaterialRequisitionLists = produceMaterialMapper.getMaterialRequisitionFromWorkSheet(workSheetId);
        System.out.println("=============================================" + produceMaterialRequisitionLists);
        for (int i = 0; i < produceMaterialRequisitionLists.size(); ) {
            //已退回数量
            BigDecimal returnNum = new BigDecimal("0");
            //已领取数量
            BigDecimal receivedNum = new BigDecimal("0");
            if (StringUtils.isNotNull(produceMaterialMapper.getReceivedNum(workSheetId, produceMaterialRequisitionLists.get(i).getProduceId()))) {
                receivedNum = BigDecimal.valueOf(produceMaterialMapper.getReceivedNum(workSheetId, produceMaterialRequisitionLists.get(i).getProduceId()));
            }
            if (StringUtils.isNotNull(produceMaterialMapper.getReturnedNum(workSheetId, produceMaterialRequisitionLists.get(i).getProduceId()))) {
                returnNum = BigDecimal.valueOf(produceMaterialMapper.getReturnedNum(workSheetId, produceMaterialRequisitionLists.get(i).getProduceId()));
            }
            produceMaterialRequisitionLists.get(i).setMaterialRequisitionNumber(
                    BigDecimal.valueOf(produceMaterialRequisitionLists.get(i).getMaterialRequisitionNumber())
                            .add(returnNum)
                            .subtract(receivedNum)
                            .doubleValue());
            if (produceMaterialRequisitionLists.get(i).getMaterialRequisitionNumber() <= 0) {
                produceMaterialRequisitionLists.remove(i);
            } else {
                i++;
            }
        }
        return produceMaterialRequisitionLists;
    }

    /**
     * 获取加工单对应物料信息
     * 新增退料单
     *
     * @param workSheetId 加工单号
     * @return
     */
    @Override
    public List<ProduceMaterialRequisitionList> getMaterialRequisitionFromWorkSheetForReturn(String workSheetId) {
        List<ProduceMaterialRequisitionList> produceMaterialRequisitionLists = produceMaterialMapper.getMaterialRequisitionFromWorkSheet(workSheetId);
        for (int i = 0; i < produceMaterialRequisitionLists.size(); ) {
            //已退回数量
            BigDecimal returnNum = new BigDecimal("0");
            //已领取数量
            BigDecimal receivedNum = new BigDecimal("0");
            if (StringUtils.isNotNull(produceMaterialMapper.getReceivedNum(workSheetId, produceMaterialRequisitionLists.get(i).getProduceId()))) {
                receivedNum = BigDecimal.valueOf(produceMaterialMapper.getReceivedNum(workSheetId, produceMaterialRequisitionLists.get(i).getProduceId()));
            }
            if (StringUtils.isNotNull(produceMaterialMapper.getReturnedNum(workSheetId, produceMaterialRequisitionLists.get(i).getProduceId()))) {
                returnNum = BigDecimal.valueOf(produceMaterialMapper.getReturnedNum(workSheetId, produceMaterialRequisitionLists.get(i).getProduceId()));
            }
            produceMaterialRequisitionLists.get(i).setMaterialRequisitionNumber(receivedNum.subtract(returnNum).doubleValue());
            if (produceMaterialRequisitionLists.get(i).getMaterialRequisitionNumber() <= 0) {
                produceMaterialRequisitionLists.remove(i);
            } else {
                i++;
            }
        }
        return produceMaterialRequisitionLists;
    }

}
